let lastTime = 0;
const prefixes: Array<string> = 'webkit moz ms o'.split(' '); //各浏览器前缀

interface IBrowserPrefix {
  [key: string]: string;
}

let rAF = window.requestAnimationFrame;
let cAF = window.cancelAnimationFrame;

//通过遍历各浏览器前缀，来得到requestAnimationFrame和cancelAnimationFrame在当前浏览器的实现形式
for (let i = 0; i < prefixes.length; i++) {
  if (rAF !== undefined && cAF !== undefined) {
    break;
  }
  const prefix = prefixes[i];
  rAF = rAF || window[(prefix + 'RequestAnimationFrame') as any];
  cAF = cAF || window[(prefix + 'CancelAnimationFrame') as any] || window[(prefix + 'CancelRequestAnimationFrame') as any];
}

//如果当前浏览器不支持requestAnimationFrame和cancelAnimationFrame，则会退到setTimeout
if (rAF === undefined || cAF === undefined) {
  rAF = function (callback) {
    const currTime = new Date().getTime();
    //为了使setTimteout的尽可能的接近每秒60帧的效果
    const timeToCall = Math.max(0, 16 - (currTime - lastTime));
    const id = window.setTimeout(function () {
      callback(currTime + timeToCall);
    }, timeToCall);
    lastTime = currTime + timeToCall;
    return id;
  };

  cAF = function (id) {
    window.clearTimeout(id);
  };
}

//得到兼容各浏览器的API
export const requestAnimationFrame = rAF;
export const cancelAnimationFrame = cAF;
